package example.UDPTest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UdpClient {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 8888;
        
        try (DatagramSocket socket = new DatagramSocket();
             Scanner scanner = new Scanner(System.in)) {
            
            InetAddress address = InetAddress.getByName(hostname);
            
            System.out.print("请输入要发送的消息: ");
            while (scanner.hasNextLine()) {
                String message = scanner.nextLine();
                
                // 发送数据包
                byte[] sendData = message.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(
                    sendData, sendData.length, address, port);
                socket.send(sendPacket);
                
                // 准备接收响应
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(
                    receiveData, receiveData.length);
                socket.receive(receivePacket);
                
                // 显示响应
                String response = new String(receivePacket.getData(), 0, 
                                           receivePacket.getLength());
                System.out.println("服务器响应: " + response);
                
                if ("bye".equalsIgnoreCase(message)) {
                    break;
                }
                System.out.print("请输入要发送的消息: ");
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}